/*
 * Copyright 2007-2009 Thomas Krause (thomas@berlin-reloaded.de)
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.gidoo.cms.editor.edit;

import java.io.Serializable;
import java.util.logging.Level;
import java.util.logging.Logger;
import org.apache.wicket.Page;
import org.apache.wicket.extensions.ajax.markup.html.modal.ModalWindow;
import org.gidoo.cms.GidooCMS;
import org.gidoo.cms.helper.Tools;
import org.gidoo.cms.view.ContentView;
import org.gidoo.cms.view.Preview;
import org.gidoo.cms.view.XSLTTransformFailedException;

/**
 * Page creator for the preview.
 * @author <a href="mailto:thomas@berlin-reloaded.de">Thomas Krause</a>
 */
public class PreviewPageCreator implements ModalWindow.PageCreator, Serializable
{

  private Page parentPage;
  private String content;
  private String title;
  private String pathToOrigPage;

  public PreviewPageCreator(Page parentPage, String content, String title,
    String pathToOrigPage)
  {
    this.parentPage = parentPage;
    this.content = content;
    this.title = title;
    this.pathToOrigPage = pathToOrigPage;
  }

  public Page createPage()
  {
    GidooCMS app = (GidooCMS) parentPage.getApplication();
    ContentView view = null;
    String xml = content;
    try
    {
      xml = app.transformContent(content);
      if(pathToOrigPage == null)
      {
        pathToOrigPage = "";
      }
      if(!xml.contains("<html"))
      {
        xml = "<html><body>\n" + xml + "\n</body></html>";
      }
      if(xml != null && !xml.startsWith("<?xml"))
      {
        xml = "<?xml version=\"1.0\" encoding=\"UTF-8\"?>\n\n" + xml;
      }
      xml = Tools.absolutizeImageTagHrefs(app, pathToOrigPage, xml);
      xml = xml.replaceAll("<?xml version=\"1.0\" encoding=\"UTF-8\"?>", "");
      xml = xml.replaceAll("<html><body>", "");
      xml = xml.replaceAll("</body></html>", "");
      
    }
    catch(XSLTTransformFailedException ex)
    {
      Logger.getLogger(PreviewPageCreator.class.getName()).log(Level.SEVERE, null, ex);
    }

    try
    {
      view = app.CMS_CONFIGURATION.getCMSPreviewPage().newInstance();
    }
    catch(Exception ex)
    {
      Logger.getLogger(PreviewPageCreator.class.getName()).log(Level.SEVERE, null, ex);
      view = new Preview();
    }
    view.setPreviewContent(title, xml);

    return view;
  }
}
